package xing.application.service.isv.suite;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xing.application.api.DingApi;
import xing.application.service.BaseService;
import xing.domain.isv.suite.Suite;
import xing.domain.isv.suite.SuiteTicket;
import xing.infrastructure.data.CallResult;
import xing.infrastructure.util.IdWorker;
import xing.repository.isv.suite.SuiteRepository;
import xing.repository.isv.suite.SuiteTicketRepository;
import xing.repository.isv.suite.SuiteTokenRepository;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/********************************
 * 文 件 名 :SuiteTokenService.java
 * 创 建 人：陈天龙
 * 日    期：2017/8/22
 * 描   述：套件suiteToken业务处理类
 * 版 本 号：v1.0.0
 ********************************/
@Service
public class SuiteTokenService extends BaseService{

    @Autowired
    private SuiteTokenRepository suiteTokenRepository;
    @Autowired
    private SuiteRepository suiteRepository;
    @Autowired
    private SuiteTicketRepository suiteTicketRepository;
    @Autowired
    private DingApi dingApi;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 描    述：新增或更新suiteToken
     * 创 建 人：陈天龙
     * 日    期：2017/8/23
     * @param suiteKey
     * @return CallResult
     */
    @Transactional(rollbackFor = Exception.class)
    public CallResult saveOrUpdateSuiteToken(String suiteKey)throws Exception{
        SuiteTicket suiteTicket = suiteTicketRepository.findBySuiteKey(suiteKey);
        Suite suite = suiteRepository.findBySuiteKey(suiteKey);
        //获取到suiteTicket之后需要换取suiteToken
        String suiteTokenJson = dingApi.getSuiteToken(suiteKey,suite.getSuiteSecret(),suiteTicket.getTicket());
        logger.info("获取suiteToken的数据:"+suiteTokenJson);
        JSONObject suiteToken = JSONObject.parseObject(suiteTokenJson);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND,suiteToken.getInteger("expires_in"));

        suiteTokenRepository.saveOrUpdateSuiteToken(IdWorker.nextId(),suiteKey,suiteToken.getString("suite_access_token"),calendar.getTime());

        return CallResult.ok();
    }
}
